package com.zyk.scaffold.oauth.keypool.service.impl;

import com.zyk.scaffold.common.utils.AssertUtil;
import com.zyk.scaffold.oauth.keypool.auth.JwtKeyIdsHelper;
import com.zyk.scaffold.oauth.keypool.pojo.dto.KeyIdsContext;
import com.zyk.scaffold.oauth.keypool.pojo.dto.KeyInfoDTO;
import com.zyk.scaffold.oauth.keypool.repository.KeyPoolRepository;
import com.zyk.scaffold.oauth.keypool.service.KeyPoolService;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 秘钥池功能服务封装
 */
@Slf4j
@Service
public class KeyPoolServiceImpl implements KeyPoolService {

    @Autowired
    private KeyPoolRepository keyPoolRepository;

    @Override
    public List<KeyInfoDTO> getRandomKeys(int nums) {
        return keyPoolRepository
                .getRandomKeys(nums)
                .stream()
                .peek(item -> item.setPrivateKey(null))
                .collect(Collectors.toList());
    }

    @Override
    public List<String> getPrivateKeysFromToken(String token) {
        KeyIdsContext keyIdsContext = null;
        try {
            keyIdsContext = JwtKeyIdsHelper.getKeyIdsContext(token);
        } catch (ExpiredJwtException ex) {
            log.error("token过期", ex);
            AssertUtil.error("token过期！");
        } catch (Exception e) {
            log.error("解析token失败！", e);
            AssertUtil.error("解析token失败！");
        }
        return keyPoolRepository
                .selectKeyInfo(keyIdsContext.getIds())
                .stream()
                .map(KeyInfoDTO::getPrivateKey)
                .collect(Collectors.toList());
    }
}
